#pragma once
#include <thread>
#include <iostream>
#include <string>
#include <queue>
#include <pthread.h>
#include <vector>
#include <unistd.h>
#include "APILock.hpp"
template <class T>
class BlockQueue//通过条件变量+互斥锁实现线程安全的阻塞队列，最终实现生产者与消费者模型
{
    std::queue<T> _blockqueue;
    int _cap = 3;
    pthread_mutex_t _mutex;
    pthread_cond_t _concond;
    pthread_cond_t _procond;
    int connum = 0;
    int pronum = 0;
    bool datafull()
    {
        return _blockqueue.size() == _cap;
    }
    bool empty()
    {
        return _blockqueue.size() == 0;
    }

public:
    BlockQueue(int cap = 3) : _cap(cap)
    {
        pthread_mutex_init(&_mutex, nullptr);
        pthread_cond_init(&_concond, nullptr);
        pthread_cond_init(&_procond, nullptr);
    }
    void push(T &data)
    {
        pthread_mutex_lock(&_mutex);
        // APIlock(&_mutex);
        while (datafull())
        {
            // pthread_cond_signal(&_concond);
            pthread_cond_wait(&_procond, &_mutex);
        }
        _blockqueue.push(data);
        pthread_cond_signal(&_concond);
        pthread_mutex_unlock(&_mutex);
    }
    void pop(T *out)
    {
        pthread_mutex_lock(&_mutex);
        // APIlock(&_mutex);
        while (empty())
        {
            // pthread_cond_signal(&_procond);
            pthread_cond_wait(&_concond, &_mutex);
        }
        *out = _blockqueue.front();
        _blockqueue.pop();
        pthread_cond_signal(&_procond);

        pthread_mutex_unlock(&_mutex);
    }
};